using System;
using System.Collections.Generic;
using System.Text;
using CookComputing.XmlRpc;
using System.Net;
using System.Xml;

namespace LiveSpacesToolkit
{
    /// <summary>
    /// Export posts of Live Spaces to a local XML file.
    /// </summary>
 
    class LiveSpacesExport
    {
        static void showUsage()
        {
            Console.WriteLine("\nUsage:");
            Console.WriteLine("LiveSpacesToolkit.exe -u Username -p Password -start StartPostNum -end EndPostNum -o OutputFileName");
        }
        /// <summary>
        /// Main loop
        /// </summary>
        [STAThread]
        static void Main(string[] Args)
        {
            Arguments command_line = new Arguments(Args);

            if (command_line["u"] == null || command_line["u"].Equals("true"))
            {
                Console.WriteLine("[ERROR] username not defined!");
                showUsage();
                System.Environment.Exit(-1);
            }
            if (command_line["p"] == null || command_line["p"].Equals("true"))
            {
                Console.WriteLine("[ERROR] password not defined!");
                showUsage();
                System.Environment.Exit(-1);
            }
            if (command_line["start"] == null || command_line["start"].Equals("true"))
            {
                Console.WriteLine("[ERROR] start number not defined!");
                showUsage();
                System.Environment.Exit(-1);
            }
                
            if (command_line["end"] == null || command_line["end"].Equals("true"))
            {
                Console.WriteLine("[ERROR] end number not defined!");
                showUsage();
                System.Environment.Exit(-1);
            }
            if (command_line["o"] == null || command_line["o"].Equals("true"))
            {
                Console.WriteLine("{0}", command_line["o"]);
                Console.WriteLine("[ERROR] output filename not defined!");
                showUsage();
                System.Environment.Exit(-1);
            }

            MsnSpacesMetaWeblog mw = new MsnSpacesMetaWeblog();
            string username = command_line["u"];
            string password = command_line["p"];

            mw.Credentials = new NetworkCredential(username, password);
            String uid = "";

            //Get the pre uuid
            try
            {
                Post[] posts = mw.getRecentPosts("MyBlog", username, password, 1);
                foreach (Post p in posts)
                {
                    String last_post_id = p.postid;
                    String[] temp = last_post_id.Split('!');
                    uid = temp[0];
                }
            }
            catch (XmlRpcFaultException xrfe)
            {
                Console.WriteLine("ERROR: {0}", xrfe.FaultString);
            }

            string file_name = command_line["o"];
            XmlTextWriter live_writer = new XmlTextWriter(file_name, null);
            live_writer.Formatting = Formatting.Indented;
            live_writer.Indentation = 2;
            live_writer.Namespaces = false;
            live_writer.WriteStartDocument();
            live_writer.WriteStartElement("", "LiveSpaces", "");

            int start_num = Convert.ToInt32(command_line["start"]);
            int end_num = Convert.ToInt32(command_line["end"]);

            for (int i = start_num; i <= end_num; i++)
            {
                String post_id = uid + "!" + i.ToString();
                try
                {
                    Post post = mw.getPost(post_id, username, password);
                    Console.WriteLine("Exporting {0}", post_id);
                    live_writer.WriteStartElement("", "Post", "");

                    live_writer.WriteStartElement("", "Id", "");
                    live_writer.WriteString(post_id);
                    live_writer.WriteEndElement();

                    Console.WriteLine("Title: {0}", post.title);
                    if (post.title == null)
                    {
                        post.title = "";
                    }

                    live_writer.WriteStartElement("", "Title", "");
                    live_writer.WriteString(post.title);
                    live_writer.WriteEndElement();

                    Console.WriteLine("Categories: {0}", post.categories);
                    if (post.categories == null)
                    {
                        post.categories = new string[0];
                        post.categories[0] = "";
                    }
                    live_writer.WriteStartElement("", "Categories", "");
                    foreach (string c in post.categories)
                    {
                        live_writer.WriteStartElement("", "Category", "");
                        live_writer.WriteString(c);
                        live_writer.WriteEndElement();
                    }
                    live_writer.WriteEndElement();

                    Console.WriteLine("Created Date: {0}", post.dateCreated.ToString());
                    live_writer.WriteStartElement("", "DateCreated", "");
                    live_writer.WriteString(post.dateCreated.ToString());
                    live_writer.WriteEndElement();

                    Console.WriteLine("Description:\n {0}", post.description);
                    if (post.description == null)
                    {
                        post.description = "";
                    }

                    live_writer.WriteStartElement("", "Description", "");
                    live_writer.WriteString(post.description);
                    live_writer.WriteEndElement();

                    live_writer.WriteEndElement();
                }
                catch (XmlRpcFaultException xrfe)
                {
                    continue;
                }
            }
            live_writer.WriteEndElement();
            live_writer.Flush();
            live_writer.Close();
        }
    }
}